package com.kun;

import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

//测试redis的事务
public class TestTransaction {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    class Chill {
        private Integer money;
        private Integer out;
    }

    @Test
    public void testTransaction_success() {
        Jedis jedis = JedisUtils.getJedis();
        jedis.flushDB();
        String chillString = JSON.toJSONString(new Chill(100, 0));
        jedis.set("chill:1", chillString);
        jedis.watch("chill:1");


        //1. 开启事务
        Transaction transaction = jedis.multi();

        //2. 操作事务
        Chill chill = JSON.parseObject(chillString, Chill.class);
        chill.setMoney(chill.getMoney() - 10);
        chill.setOut(chill.getOut() + 10);
        String newChillString = JSON.toJSONString(chill);
        transaction.set("chill:1", newChillString);

        //3. 执行事务
        try {
            transaction.exec();
        }catch (Exception e){
            e.printStackTrace();
            transaction.discard();
            jedis.unwatch();
        }

        //4. 验证结果
        System.out.println(jedis.get("chill:1"));

        JedisUtils.closeJedis(jedis);

    }

}
